package com.eascs.admin.o2o.submitted.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.generation.service.O2oGenerationService;
import com.eascs.admin.o2o.internal.util.BaseUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.entity.O2oPlatformRegional;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.submitted.entity.O2oLoanSubmittedEntity;
import com.eascs.admin.o2o.submitted.serviceimpl.O2oLoanSubmittedServiceImple;
import com.eascs.admin.o2o.submitted.vo.O2oLoanSubmittedVo;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.pay.entity.O2oPayVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.site.view.button.Button;
import com.eascs.site.view.button.ButtonHelper;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sequence.SequenceEntity;
import com.eascs.workflow.common.entity.wf.ProcessTemplate;
import com.eascs.workflow.common.service.sequence.SequenceService;
import com.eascs.workflow.common.service.wf.WorkFlowService;
import com.eascs.workflow.common.type.SystemModule;
import com.eascs.workflow.common.vo.ModelResult;
import com.eascs.workflow.common.vo.WFRequestParam;

@RestController
@RequestMapping("/rsubmitted")
public class O2oLoanSubmittedRestController extends BaseRestController {

	private static final Logger logger = LoggerFactory.getLogger(O2oLoanSubmittedRestController.class);

	@Autowired
	private O2oLoanSubmittedServiceImple o2oLoanSubmittedServiceImple;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oGenerationService o2oGenerationService;
	@Reference
	private WorkFlowService workFlowService;
	@Value("${o2o.submitted.approval}")
	String url;
	@Autowired
	private BaseUtils baseUtils;

	@RequestMapping("/add_view")
	public BaseRestResult<String> addView(O2oLoanSubmittedVo vo) {
		return HtmlRestResult.popHtmlFragment("submitted/add");
	}

	@RequestMapping("/add_save")
	public BaseRestResult<String> addSave(O2oLoanSubmittedVo vo) {
		logger.info("新增或修改案件报送，贷款id={}，流程id为空则为新建，流程id不为空则为更新，流程id={}", vo.getLoanappNo(), vo.getId());
		if (StringUtil.isBlank(vo.getLoanappNo())) {
			return BaseRestResult.warn("未选中贷款编号，请选中！");
		}
		if (null == vo.getCompensatoryMount()) {
			return BaseRestResult.warn("代偿金额不能为空，请填写！");
		}
		if (null == vo.getCompensatoryDate()) {
			return BaseRestResult.warn("代偿时间不能为空，请填写！");
		}
		if (null == vo.getOweMount()) {
			return BaseRestResult.warn("欠款金额不能为空，请填写！");
		}
		if (StringUtil.isBlank(vo.getContractNumber())) {
			return BaseRestResult.warn("合同编号不能为空，请填写！");
		}
		if (StringUtil.isBlank(vo.getPropertyInfo())) {
			return BaseRestResult.warn("财产信息不能为空，请填写！");
		}
		if (StringUtil.isBlank(vo.getSubmittedReason())) {
			return BaseRestResult.warn("报送理由不能为空，请填写！");
		}
		if (StringUtil.isBlank(vo.getLavReason())) {
			return BaseRestResult.warn("法律清收建议不能为空，请填写！");
		}
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityByLoanApplyNo(vo.getLoanappNo());
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(vo.getLoanappNo());
		O2oLoanUserEntity o2oLoanUserEntity = o2oLoanapplyService.findLoanUserEntity(vo.getLoanappNo(), o2oLoanapplyEntity.getLoanId());
		O2oPlatformRegional o2oPlatformRegional = o2oGenerationService.findLtd(o2oLoanapplyEntity.getLtd());
		Date date = new Date();
		int i = 0;
		if (null == o2oLoanSubmittedEntity) {
			String flowNumber = buildCode("AJBS", "DC");
			o2oLoanSubmittedEntity = new O2oLoanSubmittedEntity();
			o2oLoanSubmittedEntity.setBillCode(vo.getBillCode());
			o2oLoanSubmittedEntity.setLoanappNo(vo.getLoanappNo());
			o2oLoanSubmittedEntity.setLoanUserId(o2oLoanUserEntity.getId());
			o2oLoanSubmittedEntity.setLoanUserName(o2oLoanUserEntity.getUserFullName());
			o2oLoanSubmittedEntity.setCreateUser(UserHolder.getUser().getCname());
			o2oLoanSubmittedEntity.setCreateTime(date);
			o2oLoanSubmittedEntity.setLoanExpireDate(vo.getLoanExpireDate());
			o2oLoanSubmittedEntity.setLoanTerm(o2oLoanapplyEntity.getLoanTerm());
			o2oLoanSubmittedEntity.setIsDel(StatusContexts.O2O_NO);
			o2oLoanSubmittedEntity.setCompensatoryMount(vo.getCompensatoryMount());
			o2oLoanSubmittedEntity.setCompensatoryDate(vo.getCompensatoryDate());
			o2oLoanSubmittedEntity.setOweMount(vo.getOweMount());
			o2oLoanSubmittedEntity.setContractNumber(vo.getContractNumber());
			o2oLoanSubmittedEntity.setPropertyInfo(vo.getPropertyInfo());
			o2oLoanSubmittedEntity.setSubmittedReason(vo.getSubmittedReason());
			o2oLoanSubmittedEntity.setLavReason(vo.getLavReason());
			o2oLoanSubmittedEntity.setFlowNumber(flowNumber);
			o2oLoanSubmittedEntity.setLtd(o2oLoanapplyEntity.getLtd());
			o2oLoanSubmittedEntity.setLtdCode(o2oLoanapplyEntity.getLtdCode());
			o2oLoanSubmittedEntity.setLtdName(o2oLoanapplyEntity.getLtdName());
			o2oLoanSubmittedEntity.setOperatorName(o2oLoanapplyEntity.getOperatorName());
			o2oLoanSubmittedEntity.setOperatorNo(o2oLoanapplyEntity.getOperatorNo());
			o2oLoanSubmittedEntity.setLoanMount(o2oLoanapplyEntity.getEaMount());
			o2oLoanSubmittedEntity.setManagementType(o2oLoanapplyEntity.getOperationModel() == null ? "PTDB" : o2oLoanapplyEntity.getOperationModel());
			o2oLoanSubmittedEntity.setProvinceId(o2oPlatformRegional.getProvinceCode());
			o2oLoanSubmittedEntity.setProvinceName(o2oPlatformRegional.getProvinceName());
			o2oLoanSubmittedEntity.setFlowStatus(StatusContexts.O2O_NEW);
			i = o2oLoanSubmittedServiceImple.add(o2oLoanSubmittedEntity);
			logger.info("新增数据条数：{}，条数为1成功，为0失败！", i);
		} else {
			if (o2oLoanSubmittedEntity.getFlowStatus().equals(StatusContexts.O2O_NEW)) {
				o2oLoanSubmittedEntity.setBillCode(vo.getBillCode());
				o2oLoanSubmittedEntity.setLoanappNo(vo.getLoanappNo());
				o2oLoanSubmittedEntity.setLoanUserId(o2oLoanUserEntity.getId());
				o2oLoanSubmittedEntity.setLoanUserName(o2oLoanUserEntity.getUserFullName());
				o2oLoanSubmittedEntity.setCreateUser(UserHolder.getUser().getCname());
				o2oLoanSubmittedEntity.setCreateTime(date);
				o2oLoanSubmittedEntity.setLoanExpireDate(vo.getLoanExpireDate());
				o2oLoanSubmittedEntity.setIsDel(StatusContexts.O2O_NO);
				o2oLoanSubmittedEntity.setCompensatoryMount(vo.getCompensatoryMount());
				o2oLoanSubmittedEntity.setCompensatoryDate(vo.getCompensatoryDate());
				o2oLoanSubmittedEntity.setOweMount(vo.getOweMount());
				o2oLoanSubmittedEntity.setContractNumber(vo.getContractNumber());
				o2oLoanSubmittedEntity.setPropertyInfo(vo.getPropertyInfo());
				o2oLoanSubmittedEntity.setSubmittedReason(vo.getSubmittedReason());
				o2oLoanSubmittedEntity.setLavReason(vo.getLavReason());
				o2oLoanSubmittedEntity.setLtd(o2oLoanapplyEntity.getLtd());
				o2oLoanSubmittedEntity.setLtdCode(o2oLoanapplyEntity.getLtdCode());
				o2oLoanSubmittedEntity.setLtdName(o2oLoanapplyEntity.getLtdName());
				o2oLoanSubmittedEntity.setOperatorName(o2oLoanapplyEntity.getOperatorName());
				o2oLoanSubmittedEntity.setOperatorNo(o2oLoanapplyEntity.getOperatorNo());
				o2oLoanSubmittedEntity.setLoanMount(o2oLoanapplyEntity.getEaMount());
				o2oLoanSubmittedEntity.setManagementType(o2oLoanapplyEntity.getOperationModel() == null ? "PTDB" : o2oLoanapplyEntity.getOperationModel());
				o2oLoanSubmittedEntity.setProvinceId(o2oPlatformRegional.getProvinceCode());
				o2oLoanSubmittedEntity.setProvinceName(o2oPlatformRegional.getProvinceName());
				i = o2oLoanSubmittedServiceImple.update(o2oLoanSubmittedEntity);
				logger.info("更新数据条数：{}，条数为1成功，为0失败！", i);
			} else {
				return BaseRestResult.warn("该单已有一个流程中或流程结束，不能再次编辑");
			}
		}

		if (StringUtil.isNotBlank(vo.getType()) && i > 0) {
			if ("SUCCESS".equals(startUpRe(o2oLoanSubmittedEntity)))
				return BaseRestResult.info("保存并启动成功").andRefresh();
			else
				return BaseRestResult.warn("保存成功，启动失败，原因：" + startUpRe(o2oLoanSubmittedEntity)).andRefresh();
		} else if (i > 0) {
			return BaseRestResult.info("保存成功").andRefresh();
		} else {
			return BaseRestResult.warn("保存失败");
		}
	}

	@RequestMapping("/update_view")
	public BaseRestResult<String> updateView(O2oLoanSubmittedVo vo) {
		logger.info("修改信息id：{}", vo.getId());
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityById(vo.getId());
		ViewContext.put("vo", o2oLoanSubmittedEntity);
		return HtmlRestResult.popHtmlFragment("submitted/add");
	}

	@RequestMapping("/delete")
	public BaseRestResult<String> delete(O2oLoanSubmittedVo vo) {
		logger.info("删除信息id：{}", vo.getId());
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityById(vo.getId());
		o2oLoanSubmittedEntity.setIsDel(StatusContexts.O2O_YES);
		int i = o2oLoanSubmittedServiceImple.update(o2oLoanSubmittedEntity);
		if (i > 0) {
			return BaseRestResult.info("删除成功").andRedirect("/submitted/index");
		} else {
			return BaseRestResult.warn("删除失败");
		}
	}

	@RequestMapping("/startup")
	public BaseRestResult<String> startUp(O2oLoanSubmittedVo vo) {
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityById(vo.getId());
		if ("SUCCESS".equals(startUpRe(o2oLoanSubmittedEntity))) {
			return BaseRestResult.info("启动成功").andRefresh();
		} else
			return BaseRestResult.warn("启动失败，原因：" + startUpRe(o2oLoanSubmittedEntity));
	}

	/**
	 * @Description:
	 * 				<p>
	 *               代办已办详情
	 *               </p>
	 * @author CXW
	 * @date 2017年8月31日 上午10:49:34
	 * @version V1.0
	 */
	@RequestMapping("/approval")
	public BaseRestResult<String> approval(O2oPayVo vo) {
		O2oLoanSubmittedEntity o2oLoanSubmittedEntity = o2oLoanSubmittedServiceImple.getEntityById(vo.getReferId());
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(o2oLoanSubmittedEntity.getLoanappNo());
		O2oLoanUserEntity o2oLoanUserEntity = o2oLoanapplyService.findLoanUserEntity(o2oLoanSubmittedEntity.getLoanappNo(), o2oLoanapplyEntity.getLoanId());
		ViewContext.put("o2oLoanapplyEntity", o2oLoanapplyEntity);
		ViewContext.put("o2oLoanSubmittedEntity", o2oLoanSubmittedEntity);
		ViewContext.put("o2oLoanUserEntity", o2oLoanUserEntity);
		String agreeUrl = baseUtils.getApprovalAgreeUrl(vo.getReferId(), null, SystemModule.SYSTEM_MODULE_O2O);
		String approvalUrl = baseUtils.getApprovalUrl(vo.getNodeAuditorId(), SystemModule.SYSTEM_MODULE_O2O);
		ViewContext.put("agreeUrl", agreeUrl);
		ViewContext.put("approvalUrl", approvalUrl);
		ViewContext.put("approvalStatus", vo.getApprovalStatus());
		return HtmlRestResult.popHtmlFragment("submitted/approval");
	}

	/**
	 * @Description:
	 * 				<p>
	 *               启动流程
	 *               </p>
	 * @author CXW
	 * @date 2017年8月31日 上午10:49:22
	 * @version V1.0
	 */
	public String startUpRe(O2oLoanSubmittedEntity o2oLoanSubmittedEntity) {
		User user = UserHolder.getUser();
		logger.info("启动流程开始，启动id：{}", o2oLoanSubmittedEntity.getId());
		String massage = "";
		WFRequestParam param = new WFRequestParam();
		param.setReferId(o2oLoanSubmittedEntity.getId());
		param.setReferCode(o2oLoanSubmittedEntity.getFlowNumber());
		param.setReferUrl(url);
		param.setSystemModule(ProcessTemplate.SYSTEM_MODULE_O2O);
		param.setProcessType("CASE_SUBMIT");
		param.setAppliedby(user.getNo());
		param.setAppliedbyName(user.getCname());
		param.setOrgNo(o2oLoanSubmittedEntity.getLtd());
		List<String> deleteParmList = new ArrayList<String>();
		if (!"PTDB".equals(o2oLoanSubmittedEntity.getManagementType())) {// 共享模式需要过“平台复审”节点，其他模式不用过“平台复审”节点
			deleteParmList.add("AJBS_PTFS");// 平台复审
			
		}
		O2oLoanapplyEntity loanapplyEntity = o2oLoanapplyService.findById(o2oLoanSubmittedEntity.getLoanappNo());
		if(loanapplyEntity==null){
			logger.info("启动流程失败,案件报送关联的主单未找到");
			massage = "启动流程失败,案件报送关联的主单未找到";
			return massage;
		}else if (!(StatusContexts.LOAN_TYPE_BP.equals(loanapplyEntity.getLoanType())||StatusContexts.LOAN_TYPE_BP_JX.equals(loanapplyEntity.getLoanType())||StatusContexts.LOAN_TYPE_SG.equals(loanapplyEntity.getLoanType())||StatusContexts.LOAN_TYPE_YC.equals(loanapplyEntity.getLoanType())||StatusContexts.LOAN_TYPE_SC.equals(loanapplyEntity.getLoanType()))) {// 品牌贷款需要过“总部业务审”节点，其他不用过“总部业务审”节点
			deleteParmList.add("AJBS_ZBYWS");// 总部业务审
		}
		param.setExcludeNodeCodeList(deleteParmList);
		StringBuffer appliedDes = new StringBuffer("借款人:");
		appliedDes.append(o2oLoanSubmittedEntity.getLoanUserName());
		param.setAppliedDes(appliedDes.toString());
		ModelResult<Boolean> modelResult = workFlowService.instance(param);
		if (modelResult.isSuccess()) {
			o2oLoanSubmittedEntity.setFlowStartTime(new Date());
			o2oLoanSubmittedEntity.setFlowStatus(StatusContexts.O2O_BANK_RUN);
			o2oLoanSubmittedEntity.setFlowStartUser(UserHolder.getUser().getCname());
			o2oLoanSubmittedServiceImple.update(o2oLoanSubmittedEntity);
			massage = "SUCCESS";
		} else {
			massage = modelResult.getErrMsg();
		}
		logger.info("启动流程完成，是否成功：{}，原因：{}", modelResult.isSuccess(), modelResult.getErrMsg());
		return massage;
	}

	@RequestMapping("/buttons")
	public BaseRestResult<String> buttons(O2oLoanSubmittedVo vo) {
		List<Button> buttons = new ArrayList<>();
		Button startUpBtn = ButtonHelper.createAjaxButton("启动案件报送", "/rsubmitted/startup?id=" + vo.getId(), "startUpSubmitted");
		Button editBtn = ButtonHelper.createAjaxButton("编辑案件报送", "/rsubmitted/update_view?id=" + vo.getId(), "editSubmitted");
		Button deleteBtn = ButtonHelper.createAjaxConfirmButton("删除案件报送", "/rsubmitted/delete?id=" + vo.getId(), "deleteSubmitted");
		deleteBtn.setConfirmMessage("数据删除不可修复，确认删除吗？");
		buttons.add(startUpBtn);
		buttons.add(editBtn);
		buttons.add(deleteBtn);
		ViewContext.put("submittedButtons", buttons);
		return new HtmlRestResult("submitted/buttons");
	}

	@RequestMapping("/searchByBillCodecommon")
	public BaseRestResult<List<Object[]>> searchByBillCodecommon(String code) {
		List<Object[]> objsList = new ArrayList<>();
		if (!StringUtils.isEmpty(code)) {
			objsList = o2oLoanSubmittedServiceImple.findscommon(code);
		}
		return BaseRestResult.buildRestResult(objsList);
	}

	/**
	 * 生成贷款编号
	 * 
	 * @param code
	 * @param type
	 * @return
	 */
	public String buildCode(String code, String type) {
		String bill = StringUtils.getFourBitYearMonth(new Date());
		String prefix = code + "-" + type + "-" + bill;
		String flag = sequenceService.getSeq(SequenceEntity.O2O_LOAN_NO, 5, prefix);
		if (flag == null) {
			throw new RuntimeException();
		}
		return flag;
	}
}
